#!/usr/bin/env python
# encoding: utf-8

import time
import locale
import json
import subprocess
import re


def main(env):
	def getTimeZone(zone):
		if env["constants"]["platform"] != "win":
			text = open(env["static"]["cwDate_tzPath"]).read()
			for match in re.finditer(r"(?m)^.+?\t.+?\t((?:.+/)?(\S+))",text):
				(result,candidate) = match.groups()
				if zone==candidate.upper().translate(None,"-_"):
					return result
	
	loc = (env["prefs"]["cwDate_locale"] if env["prefs"]["cwDate_locale"] else env["static"]["cw_locale"])
	locale.setlocale(locale.LC_ALL,str(loc))
	hourOrDate = ("hour" if env["meta"]["actualPoorName"] == env["static"]["cwDate_cwHourPoorName"] else "date")
	format = env["prefs"]["cwDate_%sFormat" % hourOrDate].encode("utf8")
	tz = getTimeZone(env["meta"]["poorSuffix"])
	if tz is None:
		result = time.strftime(format).decode("utf8")
	else:
		internalFormat = "%Y:%m:%d:%H:%M:%S"
		cmd = 'TZ=%s date "+%s"' % (tz,internalFormat)
		output = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).communicate()[0]
		result = time.strftime(format,time.strptime(output.strip(),internalFormat)).decode("utf8")
	if hourOrDate == "date":
		return [("append",result)]
	if tz is None:
		return [("tooltip",result)]
	return [("tooltip","%s (%s)" % (result,tz))]
